<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/14
 * Time: 11:18
 */
require_once './Redis.php';
$redis = new Rediss();
//开启WebSocket 服务
$server = new Swoole\WebSocket\Server("0.0.0.0", 9505);
// 监听客户端链接并打开(有客服端有链接就会触发)
$server->on('open', function (Swoole\WebSocket\Server $server, $request) {
//    链接成功 处理业务逻辑
    global $redis;
    $token = $request->get['token'];
//    echo $token;
    $tokenRes =$redis->get('token_'.$token);
    if (empty($tokenRes)) { //token不存在关闭链接
        $server->close($request->fd);
    }else{
        $redis->set('fd_'.$tokenRes['username'],['fd'=>$request->fd,'token'=>$token,'username'=>$tokenRes['username'],'nickname'=>$tokenRes['nickname']]);
        $redis->set($request->fd,'fd_'.$tokenRes['username']);
        $userName =[];
        // 获取当前在线用户
        foreach ($server->connections as $fd){
            // 获取用户信息
            $userInfo = $redis->get($redis->get($fd));
            $userName[$fd]['nickname']=$userInfo['nickname'];
            $userName[$fd]['username']=$userInfo['username'];
        }
        foreach ($userName as $k=>$v){
            if ($request->fd != $k) {
                $server->push($k,news('','',$userName,10000));
            }
        }
        $server->push($request->fd, news('管理员','欢迎来到匿名聊天室',$userName));
    }
});

//监听客服端发送的消息  $frame 接受客户端发送的消息
$server->on('message', function (Swoole\WebSocket\Server $server, swoole_websocket_frame $frame) {
    global $redis;
    $userInfo = $redis->get($redis->get($frame->fd));//获取当前用户昵称v
    $acceptData = json_decode($frame->data,true); //接受消息数据
    $sendData = news($userInfo['nickname'],['toFrom'=>$frame->fd,'content'=>$acceptData['content']]);//组装发送数据
    echo $acceptData['toFrom'];
    echo '<br>';
    $server->push((int)$acceptData['toFrom'], $sendData);
});

//客服端关闭链接
$server->on('close', function (Swoole\WebSocket\Server $server, $fd) {
    global $redis;
    $faData= $redis->get($fd);
    $res = $redis->get($faData);
    if ($res['fd']==$fd) {
        $redis->del($fd);//删除fd数据
        $redis->del($faData);//删除用户绑定数据
        $redis->del('token_'.$res['token']);//删除token数据
    }
    $server->close($fd,true);
    foreach ($server->connections as $fds){
        // 获取用户信息
        $userInfo = $redis->get($redis->get($fds));
        if (!empty($userInfo)) {
            $userName[$fds]['nickname']=$userInfo['nickname'];
            $userName[$fds]['username']=$userInfo['username'];
        }
    }
    if (!empty($userName)) {
        foreach ($userName as $k=>$v){
            if ($fd != $k) {
                $server->push($k,news('','',$userName,10000));
            }
        }
    }

});
$server->start();


function news($user,$content,$other=[],$code=1){
    $data =[
        'code'=>$code ,//普通消息 10000系统消息
        'user'=>$user,
        'content'=>$content,
        'other'=>$other
    ];
    if (empty($other)) {
        unset($data['other']);
    }
    return json_encode($data);
}


